/**
 * Copyright (C), 2015-2024, XXX有限公司
 * FileName: ExportData
 * Author:   mac
 * Date:     2024/3/19 17:20
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.finsiot.tools.taos.migration;

import com.finsiot.tools.taos.migration.bean.TableRelation;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author zhangtianchang
 * @create 2024/3/19
 * @since 1.0.0
 */
@Slf4j
public class ExportData {

    private final static String data = "/data";
    Connection connection;
    String filePath;
    static List<String> filedList = new ArrayList<>();
    public ExportData(Connection connection, String filePath){
        this.connection=connection;

        File ddlFile = new File(filePath + data);
        if (!ddlFile.getParentFile().exists()) {
            ddlFile.getParentFile().mkdir();
        }
        if (ddlFile.exists()) {
            ddlFile.delete();
        }
        ddlFile.mkdir();

        this.filePath=filePath;
    }

    void exportData(HashMap<String, TableRelation> tableRelationHashMap, int days, String precision) throws SQLException {

        Statement statement = connection.createStatement();
        int i = 1;
        for (String table : tableRelationHashMap.keySet()) {
            log.info("第" + i + "超级表导出任务创建:" + table);

            filedList.clear();
            filedList.addAll(getFiledTagInfo(statement, table));

           TableRelation tableRelation = tableRelationHashMap.get(table);
            if(!tableRelation.getSonTableList().isEmpty()){

                for (String sonTable : tableRelation.getSonTableList()) {
                    Util.tableWrite2File(statement, table, sonTable, filedList,tableRelation.getTagList(),tableRelation.getTagValueList(), filePath, days, precision);
                }
            }
            i++;
        }
        statement.close();

    }

    private List<String> getFiledTagInfo(Statement statement, String stable) throws SQLException {

        List<String> filedList=new ArrayList<>();

        ResultSet rs =statement.executeQuery("describe "+stable);
        ResultSetMetaData metaData = rs.getMetaData();
        while (rs.next()) {
            String columnName = metaData.getColumnLabel(1);
            String note = rs.getNString(4);

            if(note.equalsIgnoreCase("TAG")){
//                tagList.add(rs.getNString(columnName));
                continue;
            }else {
                filedList.add(rs.getNString(columnName));
            }
        }
        rs.close();

        return filedList;
    }
}